<template>
  <div class="template-edit-container">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑问卷模板' : '创建问卷模板' }}</h2>
      <div class="header-actions">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <el-button type="primary" @click="handleSave" :loading="loading" icon="Check">保存</el-button>
        <el-button @click="handlePreview" icon="View">预览</el-button>
      </div>
    </div>

    <div class="template-editor">
      <el-card v-loading="loading">
        <el-form
          ref="templateFormRef"
          :model="templateForm"
          :rules="templateRules"
          label-width="100px"
        >
          <!-- 基本信息 -->
          <div class="form-section">
            <h3 class="section-title">基本信息</h3>
            <el-form-item label="问卷标题" prop="title">
              <el-input v-model="templateForm.title" placeholder="请输入问卷标题" />
            </el-form-item>
            <el-form-item label="问卷描述" prop="description">
              <el-input
                v-model="templateForm.description"
                type="textarea"
                :rows="3"
                placeholder="请输入问卷描述"
              />
            </el-form-item>
          </div>

          <!-- 题目列表 -->
          <div class="form-section">
            <div class="section-header">
              <h3 class="section-title">题目列表</h3>
              <el-button type="primary" icon="Plus" size="small" @click="handleAddQuestion">
                添加题目
              </el-button>
            </div>

            <div v-if="templateForm.questions.length === 0" class="empty-questions">
              <el-empty description="暂无题目，请点击'添加题目'按钮添加" />
            </div>

            <div
              v-for="(question, index) in templateForm.questions"
              :key="index"
              class="question-item"
            >
              <div class="question-header">
                <div class="question-index">{{ index + 1 }}</div>
                <div class="question-title">{{ getQuestionTypeText(question.questionType) }}</div>
                <div class="question-actions">
                  <el-button
                    v-if="index > 0"
                    type="info"
                    size="small"
                    icon="Top"
                    circle
                    @click="moveQuestionUp(index)"
                    title="上移"
                  />
                  <el-button
                    v-if="index < templateForm.questions.length - 1"
                    type="info"
                    size="small"
                    icon="Bottom"
                    circle
                    @click="moveQuestionDown(index)"
                    title="下移"
                  />
                  <el-button
                    type="danger"
                    size="small"
                    icon="Delete"
                    circle
                    @click="removeQuestion(index)"
                    title="删除"
                  />
                </div>
              </div>

              <el-form-item 
                :prop="`questions.${index}.questionText`" 
                :rules="[{ required: true, message: '请输入题目内容', trigger: 'blur' }]"
              >
                <el-input
                  v-model="question.questionText"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入题目内容"
                />
              </el-form-item>

              <el-form-item label="题目类型">
                <el-select v-model="question.questionType" placeholder="请选择题目类型">
                  <el-option label="单选题" value="single" />
                  <el-option label="多选题" value="multiple" />
                  <el-option label="文本题" value="text" />
                </el-select>
              </el-form-item>

              <el-form-item label="是否必填">
                <el-switch v-model="question.isRequired" />
              </el-form-item>

              <!-- 选项列表 (仅单选和多选题) -->
              <div v-if="question.questionType === 'single' || question.questionType === 'multiple'">
                <div class="options-header">
                  <span>选项列表</span>
                  <el-button type="primary" size="small" @click="addOption(index)" plain>
                    添加选项
                  </el-button>
                </div>

                <div v-if="!question.options || question.options.length === 0" class="empty-options">
                  <el-alert title="请添加至少一个选项" type="warning" :closable="false" />
                </div>

                <div
                  v-for="(option, optionIndex) in question.options"
                  :key="optionIndex"
                  class="option-item"
                >
                  <el-input
                    v-model="question.options[optionIndex]"
                    placeholder="请输入选项内容"
                    class="option-input"
                  />
                  <el-button
                    type="danger"
                    icon="Delete"
                    size="small"
                    circle
                    @click="removeOption(index, optionIndex)"
                  />
                </div>
              </div>
            </div>
          </div>
        </el-form>
      </el-card>
    </div>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="问卷预览"
      width="700px"
      destroy-on-close
    >
      <div v-if="templateForm" class="preview-container">
        <h2 class="preview-title">{{ templateForm.title || '问卷标题' }}</h2>
        <p class="preview-description">{{ templateForm.description || '问卷描述' }}</p>

        <div v-if="templateForm.questions && templateForm.questions.length > 0" class="questions-list">
          <div 
            v-for="(question, index) in templateForm.questions" 
            :key="index" 
            class="question-item"
          >
            <div class="question-header">
              <span class="question-index">{{ index + 1 }}</span>
              <span class="question-text">{{ question.questionText }}</span>
              <span v-if="question.isRequired" class="required-mark">*</span>
            </div>

            <!-- 单选题 -->
            <div v-if="question.questionType === 'single'" class="question-options">
              <el-radio-group v-model="previewAnswers[index]">
                <div v-for="(option, optionIndex) in question.options" :key="optionIndex" class="option-item">
                  <el-radio :label="option">{{ option }}</el-radio>
                </div>
              </el-radio-group>
            </div>

            <!-- 多选题 -->
            <div v-else-if="question.questionType === 'multiple'" class="question-options">
              <el-checkbox-group v-model="previewAnswers[index]">
                <div v-for="(option, optionIndex) in question.options" :key="optionIndex" class="option-item">
                  <el-checkbox :label="option">{{ option }}</el-checkbox>
                </div>
              </el-checkbox-group>
            </div>

            <!-- 文本题 -->
            <div v-else-if="question.questionType === 'text'" class="question-options">
              <el-input
                v-model="previewAnswers[index]"
                type="textarea"
                :rows="3"
                placeholder="请输入您的回答"
              />
            </div>
          </div>
        </div>

        <div v-else class="empty-questions">
          <el-empty description="该问卷暂无题目" />
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handlePreviewSubmit">预览提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/user'
import { 
  getQuestionnaireTemplate, 
  createQuestionnaireTemplate, 
  updateQuestionnaireTemplate 
} from '@/api/questionnaire'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 当前用户ID和角色
const userId = computed(() => userStore.userId)
const userRole = computed(() => userStore.role)

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id)
const templateId = computed(() => route.params.id)

// 添加日志输出以便调试
console.log('路由参数:', route.params)
console.log('模板ID:', templateId.value)
console.log('是否为编辑模式:', isEdit.value)

// 加载状态
const loading = ref(false)

// 表单引用
const templateFormRef = ref(null)

// 表单数据
const templateForm = reactive({
  title: '',
  description: '',
  questions: []
})

// 表单校验规则
const templateRules = {
  title: [
    { required: true, message: '请输入问卷标题', trigger: 'blur' },
    { max: 100, message: '标题长度不能超过100个字符', trigger: 'blur' }
  ],
  description: [
    { max: 255, message: '描述长度不能超过255个字符', trigger: 'blur' }
  ]
}

// 预览对话框
const previewDialogVisible = ref(false)
const previewAnswers = ref([])

// 初始化
onMounted(async () => {
  if (isEdit.value && templateId.value) {
    await fetchTemplateDetail()
  } else {
    // 新建问卷时添加一个默认题目
    addDefaultQuestion()
  }
})

// 获取问卷模板详情
const fetchTemplateDetail = async () => {
  loading.value = true
  try {
    const res = await getQuestionnaireTemplate(templateId.value)
    if (res.code === 200) {
      // 填充表单数据
      Object.assign(templateForm, res.data)
      // 确保每个题目都有正确的排序号
      templateForm.questions.forEach((question, index) => {
        question.sortOrder = index + 1
      })
    } else {
      ElMessage.error(res.msg || '获取问卷模板详情失败')
      goBack()
    }
  } catch (error) {
    console.error('获取问卷模板详情出错:', error)
    ElMessage.error('获取问卷模板详情失败')
    goBack()
  } finally {
    loading.value = false
  }
}

// 添加默认题目
const addDefaultQuestion = () => {
  templateForm.questions.push({
    questionText: '',
    questionType: 'single',
    options: ['选项1', '选项2'],
    isRequired: true,
    sortOrder: templateForm.questions.length + 1
  })
}

// 返回上一页
const goBack = () => {
  router.push('/questionnaire/template-list')
}

// 保存问卷模板
const handleSave = async () => {
  if (!templateFormRef.value) return

  await templateFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请填写必填项')
      return
    }

    // 验证问卷至少有一个题目
    if (templateForm.questions.length === 0) {
      ElMessage.error('问卷必须包含至少一个题目')
      return
    }

    // 验证所有选择题都有选项
    for (const question of templateForm.questions) {
      if ((question.questionType === 'single' || question.questionType === 'multiple') 
          && (!question.options || question.options.length === 0)) {
        ElMessage.error(`题目"${question.questionText || '未命名'}"必须包含至少一个选项`)
        return
      }
    }

    // 更新问题排序
    templateForm.questions.forEach((question, index) => {
      question.sortOrder = index + 1
    })

    loading.value = true
    try {
      let res
      if (isEdit.value) {
        console.log('正在更新问卷模板，ID:', templateId.value, '数据:', JSON.stringify(templateForm))
        res = await updateQuestionnaireTemplate(templateId.value, templateForm)
      } else {
        res = await createQuestionnaireTemplate(templateForm)
      }

      console.log('请求响应:', res)
      if (res.code === 200) {
        ElMessage.success(isEdit.value ? '更新问卷模板成功' : '创建问卷模板成功')
        goBack()
      } else {
        ElMessage.error(res.msg || (isEdit.value ? '更新问卷模板失败' : '创建问卷模板失败'))
      }
    } catch (error) {
      console.error(isEdit.value ? '更新问卷模板出错:' : '创建问卷模板出错:', error)
      ElMessage.error(isEdit.value ? '更新问卷模板失败' : '创建问卷模板失败')
    } finally {
      loading.value = false
    }
  })
}

// 添加新题目
const handleAddQuestion = () => {
  templateForm.questions.push({
    questionText: '',
    questionType: 'single',
    options: ['选项1', '选项2'],
    isRequired: true,
    sortOrder: templateForm.questions.length + 1
  })
}

// 移除题目
const removeQuestion = (index) => {
  ElMessageBox.confirm(
    '确定要删除该题目吗?',
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      templateForm.questions.splice(index, 1)
      // 更新剩余题目的排序
      templateForm.questions.forEach((q, i) => {
        q.sortOrder = i + 1
      })
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 上移题目
const moveQuestionUp = (index) => {
  if (index <= 0) return
  const temp = templateForm.questions[index]
  templateForm.questions[index] = templateForm.questions[index - 1]
  templateForm.questions[index - 1] = temp
  // 更新排序
  templateForm.questions.forEach((q, i) => {
    q.sortOrder = i + 1
  })
}

// 下移题目
const moveQuestionDown = (index) => {
  if (index >= templateForm.questions.length - 1) return
  const temp = templateForm.questions[index]
  templateForm.questions[index] = templateForm.questions[index + 1]
  templateForm.questions[index + 1] = temp
  // 更新排序
  templateForm.questions.forEach((q, i) => {
    q.sortOrder = i + 1
  })
}

// 添加选项
const addOption = (questionIndex) => {
  const question = templateForm.questions[questionIndex]
  if (!question.options) {
    question.options = []
  }
  question.options.push(`选项${question.options.length + 1}`)
}

// 移除选项
const removeOption = (questionIndex, optionIndex) => {
  const question = templateForm.questions[questionIndex]
  question.options.splice(optionIndex, 1)
}

// 获取题目类型文本
const getQuestionTypeText = (type) => {
  const typeMap = {
    'single': '单选题',
    'multiple': '多选题',
    'text': '文本题'
  }
  return typeMap[type] || '未知题型'
}

// 预览问卷
const handlePreview = () => {
  if (templateForm.questions.length === 0) {
    ElMessage.warning('问卷暂无题目，无法预览')
    return
  }
  
  previewAnswers.value = new Array(templateForm.questions.length).fill(null).map((_, i) => {
    const question = templateForm.questions[i]
    if (question.questionType === 'multiple') {
      return []
    }
    return null
  })
  
  previewDialogVisible.value = true
}

// 预览提交
const handlePreviewSubmit = () => {
  // 判断必填项是否已填写
  const emptyRequired = templateForm.questions.findIndex((q, index) => {
    if (!q.isRequired) return false

    const answer = previewAnswers.value[index]
    if (q.questionType === 'single' || q.questionType === 'text') {
      return !answer
    } else if (q.questionType === 'multiple') {
      return !answer || answer.length === 0
    }
    return false
  })

  if (emptyRequired !== -1) {
    ElMessage.warning(`第 ${emptyRequired + 1} 题是必填项，请填写完整`)
    return
  }

  ElMessage.success('预览问卷提交成功')
  previewDialogVisible.value = false
}
</script>

<style scoped>
.template-edit-container {
  animation: fadeIn 0.3s ease-out;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: var(--card-background);
  padding: 20px 24px;
  border-radius: var(--radius-medium);
  box-shadow: var(--shadow-base);
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: var(--text-primary);
  display: flex;
  align-items: center;
}

.page-header h2::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 20px;
  background: linear-gradient(180deg, var(--primary-color), #4d7aff);
  margin-right: 12px;
  border-radius: 2px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.template-editor {
  margin-bottom: 24px;
}

.form-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px dashed #ddd;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  font-size: 18px;
  font-weight: 500;
  color: var(--text-primary);
  margin: 0 0 16px 0;
}

.empty-questions {
  text-align: center;
  padding: 30px 0;
  color: #999;
}

.question-item {
  margin-bottom: 24px;
  padding: 20px;
  border-radius: 8px;
  background-color: #f8f8f8;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.question-index {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 14px;
  background-color: var(--primary-color);
  color: white;
  font-weight: bold;
  margin-right: 12px;
}

.question-title {
  flex: 1;
  font-size: 16px;
  font-weight: 500;
}

.question-actions {
  display: flex;
  gap: 8px;
}

.options-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px 0;
}

.empty-options {
  margin: 16px 0;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.option-input {
  flex: 1;
  margin-right: 10px;
}

/* 预览样式 */
.preview-container {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.preview-title {
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  margin-bottom: 12px;
}

.preview-description {
  font-size: 14px;
  color: #666;
  text-align: center;
  margin-bottom: 24px;
}

.questions-list {
  margin-top: 20px;
}

.question-item {
  margin-bottom: 24px;
  padding: 16px;
  border-radius: 8px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.question-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
}

.question-index {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background-color: var(--primary-color);
  color: white;
  border-radius: 50%;
  font-size: 14px;
  margin-right: 8px;
  flex-shrink: 0;
}

.question-text {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  flex: 1;
}

.required-mark {
  color: #f56c6c;
  margin-left: 4px;
}

.question-options {
  padding-left: 32px;
}

.option-item {
  margin-bottom: 8px;
}
</style> 